package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.conf.WfNextStepVo;
import com.miplus.ccrm.core.controller.vo.credit.CrdCaseResVo;
import com.miplus.ccrm.core.controller.vo.credit.FiTaskReqVo;
import com.miplus.ccrm.core.controller.vo.credit.FiTaskResVo;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.mapper.FiReliefMapper;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.FiWorkFlowCase;
import com.miplus.ccrm.core.service.conf.MsgAlertsService;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import com.miplus.ccrm.core.service.crd.FiTaskService;
import com.miplus.ccrm.core.service.file.FiApplyAttService;
import com.miplus.ccrm.core.service.strategy.CpCalllistService;
import com.miplus.ccrm.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
* @author pc
* @description 针对表【fi_relief(减免申请表)】的数据库操作Service实现
* @createDate 2024-04-09 20:06:35
*/
@Slf4j
@Service
public class FiReliefServiceImpl extends MPJBaseServiceImpl<FiReliefMapper, FiRelief>
    implements FiReliefService{
    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private CpCalllistService cpCalllistService;
    @Resource
    private FiWorkFlowCase fiWorkFlowCase;
    @Resource
    private FiApplyAttService fiApplyAttService;
    @Resource
    private MsgAlertsService msgAlertsService;
    @Resource
    private ExportService exportService;
    @Resource
    private FiImportHistService fiImportHistService;

    @Override
    public IPage<FiReliefResVo> fiReliefList(JSysUser user, FiApplyReqVo paras)
    {
        String $usrid=user.getUsrid();
        String cardstar= JUsrPerm.getPermission(user,JUsrPerm.DISSTAR_CARD);
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                FiReliefResVo.class,
                new MPJLambdaWrapper<FiRelief>()
                        .selectAs("fun_getnames('FI.RELIEF.STATUS',t.status)", FiReliefResVo::getStatusdsc)
                        .selectAs("fun_getnames('FI.RELIEF.REASON',t.applyreason)", FiReliefResVo::getApplyreason)
                        .selectAs("(select cl.wfid from cp_calllist cl where cl.clid=t.clid)", FiReliefResVo::getWfid)
                        .selectAs("(select g.grpname from sys_user u join sys_grp g on u.groups=g.grpid where u.usrid=t.applyusr)",FiReliefResVo::getApplygrp)
                        .selectAs("DATE_FORMAT(t.applydt,'%Y-%m-%d %H-%i-%s')",FiReliefResVo::getApplydt)
                        .selectAs("DATE_FORMAT(t.confirmdt,'%Y-%m-%d %H-%i-%s')",FiReliefResVo::getConfirmdt)
                        .selectAs("DATE_FORMAT(t.canceldt,'%Y-%m-%d %H-%i-%s')",FiReliefResVo::getCanceldt)


                        .selectAs("(ifnull( t.reliefprin,0)+ ifnull(t.relieffee, 0 )+ifnull(t.reliefoth, 0))",FiReliefResVo::getReliefamt)
                        .selectAs(String.format("fi_starSecu('%s','%s',cda.crdt_card_repe_no,'%s')", $usrid, JUsrPerm.DISSTAR_CARD, cardstar), FiReliefResVo::getCardno)
                        .leftJoin(FiCreditcases.class,"fi",FiCreditcases::getCreditcaseid,FiRelief::getFicaseid)
                        .leftJoin(ConCustomer.class,"cu",ConCustomer::getCustomernumber,FiCreditcases::getCustomernumber)
                        .leftJoin(CreditAccount.class,"cda",CreditAccount::getAcct,FiCreditcases::getCreditAcct)
                        .leftJoin(CreditAccountBalance.class,"cab",CreditAccountBalance::getAcct,FiCreditcases::getCreditAcct)
                        .selectAll(FiRelief.class)
                        .select(ConCustomer::getCustname)
                        .select(FiCreditcases::getMthsDay,
                                FiCreditcases::getOverdueStage,
                                FiCreditcases::getOverdueTotalamt,
                                FiCreditcases::getPreRepayPrincipal,
                                FiCreditcases::getPreRepayInterest,
                                FiCreditcases::getPreOverdueFee,
                                FiCreditcases::getPreRepayFee
                                )
                        .apply("fc_hasApplyView(t.applynumber,'SYS_RELIEF',t.applyusr,{0},t.status,t.confirmusr)>0",$usrid)
                        .apply(JPubUtils.IsNotEmpty(paras.getApplygrp()),"fc_hasUsrInGroup(t.applyusr,{0})>0",paras.getApplygrp())
                        .eq(JPubUtils.IsNotEmpty(paras.getFicaseid()), FiRelief::getFicaseid,paras.getFicaseid())
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()), FiRelief::getStatus,paras.getStatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getApplyusr()),FiRelief::getApplyusr,paras.getApplyusr())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), FiRelief::getApplydt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
        );
    }

    @Override
    @Transactional
    public CmdResVo fiReliefAdd(JSysUser user, FiReliefAddVo paras)
    {
        String $usrid= user.getUsrid();
        //1=待审核
        FiRelief fiRelief=selectJoinOne(FiRelief.class,
                new MPJLambdaWrapper<FiRelief>()
                        .eq(FiRelief::getFicaseid,paras.getFicaseid())
                        .eq(FiRelief::getStatus, EnumConfirmStatus.Pending.value)
        );
        //相同的案件正在审核中
        if(fiRelief!=null){
            throw new ServiceException(EnumRCode.DataPending.value, EnumRCode.DataPending.name);
        }
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_RELIEF"; //此任务是系统配置任务，不能delete
        }

        //2024-07-08
        String prem=JUsrPerm.getPermission(user,"WF.RELIEF.CONFIRM2");
        log.info("fiReliefAdd.ficase={},has={}",paras.getFicaseid(),prem);

        Integer wfid=0;
        if(JPubUtils.IsEmpty(prem)) {//需要工作流，否则跳过工作流,2024-07-08
            wfid=cpCalllistService.getCalllistWfID(clid);
        }

        //CAMPAIGN.CHANNEL=11留案
        int tasknumber=fiTaskService.addTask($usrid,clid,paras.getFicaseid(), EnumFiChannel.Relief.value);

        int ret=0;
        log.info("applyAdd:clid={},ficase={},tasknumber={},wfid={}",clid,paras.getFicaseid(),tasknumber,wfid);

        FiRelief fi = new FiRelief();
        fi.setClid(clid);
        if(paras.getReliefprin()==null){
            fi.setReliefprin(new BigDecimal(0.0));
        }else {
            fi.setReliefprin(paras.getReliefprin());
        }
        if(paras.getRelieffee()==null){
            fi.setRelieffee(new BigDecimal(0.0));
        }else {
            fi.setRelieffee(paras.getRelieffee());
        }
        if(paras.getReliefoth()==null){
            fi.setReliefoth(new BigDecimal(0.0));
        }else {
            fi.setReliefoth(paras.getReliefoth());
        }
        fi.setApplyreason(paras.getApplyreason());
        fi.setFicaseid(paras.getFicaseid());
        fi.setApplydsc(paras.getApplydsc());
        fi.setTasknumber(tasknumber);
        fi.setApplydt(new Date());
        fi.setApplyusr($usrid);
        if(JPubUtils.IsEmpty(prem)) {
            fi.setStatus(EnumConfirmStatus.New.value); //新建
        }
        else{
            fi.setStatus(EnumConfirmStatus.Pass.value); //通过
            fi.setConfirmdt(new Date());
            fi.setConfirmusr($usrid);
            fi.setConfirmdsc("自动审批通过");
            fiTaskService.updateStatus(tasknumber, $usrid, "P");
        }
        ret=baseMapper.insert(fi);

        int applynumber=fi.getApplynumber();
        fiApplyAttService.AddApplyFile(applynumber,EnumFiChannel.Relief.toString().toLowerCase(), paras.getUploadList());

        if(wfid>0){
            //wfid=0 表示此任务clid没有配置工作流，前台可以根据是否有wfid显示不通的审批流程或状态
            String status=fiWorkFlowCase.doCreate($usrid,wfid,applynumber,tasknumber);
            fi = new FiRelief();
            fi.setApplynumber(applynumber);
            fi.setStatus(Integer.parseInt(status)); //处理中
            baseMapper.updateById(fi);
        }

        return new CmdResVo(ret,Integer.toString(applynumber));
    }

    @Override
    public CmdResVo fiReliefCancel(String $usrid, FiApplyCancelVo paras)
    {
        FiRelief fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())){
            fiTaskService.updateStatus(fi.getTasknumber(),$usrid,"X");
        }
        else{
            log.warn("applyCancel:getTasknumber.isnull");
        }
        Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
        fiWorkFlowCase.doCancel($usrid,wfid,fi.getApplynumber());

        fi = new FiRelief();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(EnumConfirmStatus.Cancel.value); //取消
        fi.setCancelusr($usrid);
        fi.setCanceldt(new Date());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,fi.getApplynumber().toString());
    }

    @Override
    public CmdResVo fiReliefConfirm(String $usrid, FiApplyConfirmVo paras)
    {
        String okstatus=paras.getActionid().toString();
        boolean confirmend=true;
        FiRelief fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(paras.getCaseactid())){
            //需要走工作流
            WfNextStepVo wfNextStepVo=fiWorkFlowCase.doExec($usrid,paras.getCaseactid(),
                    paras.getActionid(),paras.getWfcaseid(),paras.getConfirmdsc()
            );
            okstatus=wfNextStepVo.getStatus();

            //可能有多级审核,3=审核全部完成
            if(!JPubUtils.IsEqual(wfNextStepVo.getType(), EnumWorkFlowStep.End.value)) {
                confirmend=false;
            }
        }
        else{
            Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
            if(wfid==null||wfid==0){//不使用工作流,这种情况下okstatus就是字典ID，直接写审核结果
                log.info("fiReliefConfirm.nouse workflow：okstatus={}",okstatus);
            }
            else{//可能配置错误或网络引起的，2024-08-29
                log.warn("fiReliefConfirm.nofind wf caseactid.");
                throw new ServiceException(EnumRCode.WfDataErr.value, EnumRCode.WfDataErr.name);
            }
        }

        //单纯就是审批流程，结果后续操作就在这里写，如果有后续反馈的，在result里面写，比如外访
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())&&confirmend) {
            fiTaskService.updateStatus(
                    fi.getTasknumber(),
                    $usrid,
                    fiWorkFlowCase.getPassStatus(okstatus)
            );

            msgAlertsService.msgAlertAdd(EnumFiChannel.Relief,
                    fi.getApplyusr(),
                    $usrid, EnumUtil.ConfirmStatusName(okstatus)
            );
        }

        fi = new FiRelief();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(Integer.parseInt(okstatus));
        fi.setConfirmusr($usrid);
        fi.setConfirmdt(new Date());
        fi.setConfirmdsc(paras.getConfirmdsc());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,paras.getApplynumber().toString());
    }

    @Override
    public CmdResVo expRelief(JSysUser user,FiApplyReqVo paras, HttpServletResponse response)
    {
        String $usrid=user.getUsrid();
        IPage<FiReliefResVo> pages=fiReliefList(user, paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"减免列表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    $usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }

        return resVo;
    }
}




